# Create your views here.
from django.db.models.aggregates import Sum
from django.http import JsonResponse
from django.db import connection
import json,requests
from rest_framework.decorators import api_view
from buildapi.models import BuildingInfo
from guestapi.models import GuestInfo
from houseapi.models import HouseInfo
from adminapi.models import User
# Create your views here.


@api_view(['POST'])
def dispatcher(request):  

    # try:
    if request.user.is_authenticated:   # 验证Token是否正确
        if request.user.is_active:
            if request.method == 'GET':
                request.params = request.GET

            # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
            elif request.method in ['POST','PUT','DELETE']:
                # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
                request.params = json.loads(request.body)


            # 根据不同的action分派给不同的函数进行处理
            action = request.params['action']
            if action == 'list':
                return HouseInfo_list(request)
            elif action == 'add':
                return HouseInfo_add(request)
            elif action == 're':  
                return HouseInfo_re(request)
            elif action == 'del':
                return HouseInfo_del(request)
            elif action == 'like':
                return HouseInfo_like(request)
            elif action == 'include':
                return HouseInfo_include(request)
            elif action == 'type':
                return HouseInfo_type(request)
            elif action == 'type_del':
                return HouseInfo_type_del(request)
            elif action == 'list_id':
                return HouseInfo_list_id(request)
            elif action == 'add_tool':
                return HouseInfo_add_tool(request)

            else:
                return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})
    else:
        return JsonResponse({'ret': 2, "msg": "token验证失败"})


def HouseInfo_add_tool(request):
    data = json.loads(request.body)
    try:
        house_id = data['house_id']
        tool_type = data['tool_type']
        re = HouseInfo.objects.get(house_id=house_id)

        if tool_type == 'electric':
            tool_SN = data['tool_SN']
            re.house_electric = tool_SN
            re.save()
        elif tool_type == 'water':
            tool_SN = data['tool_SN']
            re.house_water = tool_SN
            re.save()
        elif tool_type == 'SQL_electric':
            tool_valve = data['tool_valve']
            tool_SN = re.house_electric
        elif tool_type == 'SQL_water':
            tool_valve = data['tool_valve']
            tool_SN = re.house_water
        elif tool_type == 'value':
            tool_SN = data['tool_SN']
        else:
            return JsonResponse({
            'ret': 1,
            'msg': "tool_type不正确"
        })

        if tool_SN is not None:
            #登陆水电平台
            token = {"Authorization" : "Basic b3BlbmNsaWVudDpvcGVuY2xpZW50"}

            login = requests.post('http://www.meter-iot.cn/api/auth/oauth/token?grant_type=client_credentials&scope=open', headers=token)
            login_index = login.json()
            login_token = {"Authorization" : "Bearer {}".format(login_index['access_token'])}

            #查询对应水电表
            index = requests.get('http://www.meter-iot.cn/api/open/openapi/read/info/47c179f7b2e04f0f9d83539b084012a4/{}'.format(tool_SN), headers=login_token)
            tool_index = index.json()
            if 'code' not in tool_index:
                re.house_water_valve = 3
                re.save()
                return JsonResponse({'ret': 1, 'msg': '水电表设备异常'})
            
            if tool_type == 'electric':
                re.house_electric_valve = tool_index['data']['extendDict']['valveStatus']
                re.save()
            elif tool_type == 'water':
                re.house_water_valve = tool_index['data']['extendDict']['valveStatus']
                re.save()
            elif tool_type == 'SQL_electric':
                valve = requests.post('http://www.meter-iot.cn/api/open/openapi/valve/47c179f7b2e04f0f9d83539b084012a4/{}?valveStatus={}'.format(tool_SN,tool_valve), headers=login_token)
                tool_valve_index = valve.json()
                if 'code' not in tool_valve_index:
                    re.house_electric_valve = 3
                    re.save()
                elif tool_valve_index['code'] == 1:
                    re.house_electric_valve = 3
                    re.save()
                else:
                    re.house_electric_valve = tool_valve
                    re.save()
                return JsonResponse(tool_valve_index)
            elif tool_type == 'SQL_water':
                valve = requests.post('http://www.meter-iot.cn/api/open/openapi/valve/47c179f7b2e04f0f9d83539b084012a4/{}?valveStatus={}'.format(tool_SN,tool_valve), headers=login_token)
                tool_valve_index = valve.json()
                if 'code' not in tool_valve_index:
                    re.house_water_valve = 3
                    re.save()
                elif tool_valve_index['code'] == 1:
                    re.house_water_valve = 3
                    re.save()
                else:
                    re.house_water_valve = tool_valve
                    re.save()
                return JsonResponse(tool_valve_index)
                
            return JsonResponse(tool_index)
        else:
            return JsonResponse({
            'ret': 1,
            'msg': "未绑定水电表"
        })


    except Exception as e:
        return JsonResponse({
            'ret': 1,
            'msg': "发生异常：{}".format(e)
        })


def HouseInfo_list_id(request):
    data = json.loads(request.body)
    try:
        house_id = data['house_id']
        index = HouseInfo.objects.filter(house_id=house_id).values()
    except HouseInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':list(index)})


def HouseInfo_list(request):
    try:
        data = json.loads(request.body)
        openid = data['openid']
        page_max = int(data['page_max'])
        page = int(data['page'])
        index = HouseInfo.objects.filter(house_openid=openid).values().order_by('house_id')[page_max*page-page_max:page_max*page]
        count = HouseInfo.objects.filter(house_openid=openid).count()

        return JsonResponse({'ret':0,'data':list(index),'count':count})
    except HouseInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })


def HouseInfo_add(request):
    data = json.loads(request.body)  
    try:
        house_nbr = data['house_nbr']
        house_about_id = data['house_about_id']
        house_price = data['house_price']
        house_area = data['house_area']
        house_electric = data['house_electric']
        house_water = data['house_water']
        house_openid = data['house_openid']

        if HouseInfo.objects.filter(house_nbr=house_nbr,house_about_id=house_about_id).exists():
            return JsonResponse({'ret':2 , 'msg':"该房间编号：{} 已经存在".format(house_nbr)})
        if BuildingInfo.objects.filter(building_id=house_about_id).exists() is False:
            return JsonResponse({'ret':2 , 'msg':"该楼栋编号：{} 不存在".format(house_about_id)})
        if HouseInfo.objects.filter(house_electric=house_electric).exists():
            return JsonResponse({'ret':3,'msg':'该设备id已被绑定'})
        if HouseInfo.objects.filter(house_water=house_water).exists():
            return JsonResponse({'ret':3,'msg':'该设备id已被绑定'})
        else:
            index = BuildingInfo.objects.filter(building_id=house_about_id).values()
            building_nbr = list(index)[0]['building_nbr']

            ure = User.objects.get(openid=house_openid)

            HouseInfo.objects.create(
            house_nbr = house_nbr,
            house_openid = house_openid,
            house_price = house_price,
            house_area = house_area,
            house_mode = ure.user_mode,
            house_about_name = building_nbr,
            house_electric = house_electric,
            house_water = house_water,
            house_type = 0,
            house_electric_valve = 1,
            house_water_valve = 1,
            house_electric_last = 0,
            house_water_last = 0,
            house_about_id = house_about_id)

            count = HouseInfo.objects.filter(house_about_id=house_about_id).count()

            re = BuildingInfo.objects.get(building_id=house_about_id)
            re.building_count = count
            re.save()
            return JsonResponse({'ret':0})

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "信息添加失败，发生异常:{}".format(e)
            })


def HouseInfo_re(request):
    data = json.loads(request.body)  
    cursor = connection.cursor()
    try:
        key = list(data['key'])
        value = list(data['value'])
        house_id = data['house_id']

        con = HouseInfo.objects.filter(house_id=house_id).values()
        house = list(con)[0]

        if len(key) > 0 :
            for i in range(len(key)):

                if key[i] == 'house_guest_id':
                    if house['house_guest_name'] and house['house_guest_id'] is not None:
                        return JsonResponse({
                            'ret': 2,
                            'msg': "请先注销原有住户信息再新增"
                        })
                    elif GuestInfo.objects.filter(guest_id=value[i]).exists():
                        
                        house_date1 = data['house_date1']
                        house_date2 = data['house_date2']
                        
                        index = GuestInfo.objects.filter(guest_id=value[i]).values()
                        
                        cursor.execute(" UPDATE house_info SET house_guest_id = '{}' WHERE house_id = '{}' ".format(value[i],house_id))
                        cursor.execute(" UPDATE house_info SET house_guest_name = '{}' WHERE house_id = '{}' ".format(list(index)[0]['guest_name'],house_id))
                        cursor.execute(" UPDATE house_info SET house_date1 = '{}' WHERE house_id = '{}' ".format(house_date1,house_id))
                        cursor.execute(" UPDATE house_info SET house_date2 = '{}' WHERE house_id = '{}' ".format(house_date2,house_id))
                        cursor.execute(" UPDATE house_info SET house_type = '1' WHERE house_id = '{}' ".format(house_id))

                        count = HouseInfo.objects.filter(house_about_id=house['house_about_id'],house_type=1).count()

                        re = BuildingInfo.objects.get(building_id=house['house_about_id'])
                        re.building_idle_count = count
                        re.save()
                        
                        gre = GuestInfo.objects.get(guest_id=value[i])
                        gre.guest_about_house = house['house_nbr']
                        gre.guest_about_house_id = house['house_id']
                        gre.guest_about_building = house['house_about_name']
                        gre.guest_about_building_id = house['house_about_id']
                        gre.save()
                    else:
                        return JsonResponse({'ret':2,'msg':'请先新增人员'})
                
                cursor.execute(" UPDATE house_info SET {} = '{}' WHERE house_id = '{}' ".format(key[i],value[i],house_id))

        return JsonResponse({'ret':0})
    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "信息修改失败，发生异常:{}".format(e)
            })

def HouseInfo_del(request):
    data = json.loads(request.body)  
    try:
        house_id = list(data['house_id'])

        if len(house_id) > 0 :
            for i in range(len(house_id)):
                value = HouseInfo.objects.filter(house_id=house_id[i]).values()
                house = list(value)[0]

                if GuestInfo.objects.filter(guest_id=house['house_guest_id']).exists():
                    return JsonResponse({
                    'ret': 2,
                    'msg': "请先删除或更改：{} 已关联的住户".format(house_id[i])
                    })
                index = HouseInfo.objects.get(house_id=house_id[i])
                index.delete()

            count = BuildingInfo.objects.filter(building_id=house['house_about_id']).values()
            building_count = list(count)[0]['building_count']

            re = BuildingInfo.objects.get(building_id=house['house_about_id'])
            re.building_count = int(building_count) - len(house_id)
            re.save()
            
    except HouseInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "信息删除失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0})

def HouseInfo_like(request):
    data = json.loads(request.body)
    try:
        openid = data['openid']
        house_nbr = data['house_nbr']
        house_about_id = data['house_about_id']
        index = HouseInfo.objects.filter(house_nbr__icontains=house_nbr,house_about_id=house_about_id,house_openid=openid).values()
    except HouseInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "模糊查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':list(index)})


def HouseInfo_include(request):
    data = json.loads(request.body)
    try:
        house_about_id = data['house_about_id']
        index = HouseInfo.objects.filter(house_about_id=house_about_id).values()
    except HouseInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':list(index)})


def HouseInfo_type(request):
    data = json.loads(request.body)
    try:
        house_type = data['house_type']
        house_about_id = data['house_about_id']
        index = HouseInfo.objects.filter(house_about_id=house_about_id,house_type=house_type).values()
    except Exception as e:
        return JsonResponse({
            'ret': 1,
            'msg': "发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':list(index)})


def HouseInfo_type_del(request):
    data = json.loads(request.body)
    try:
        house_id = data['house_id']
        re = HouseInfo.objects.get(house_id=house_id)
        
        gre = GuestInfo.objects.get(guest_id=re.house_guest_id)
        gre.guest_about_house = None
        gre.guest_about_building = None
        gre.save()
        
        re.house_date1 = None
        re.house_date2 = None
        re.house_type = 0
        re.house_guest_id = None
        re.house_guest_name = None
        re.save()
        
        value = HouseInfo.objects.filter(house_id=house_id).values()
        house = list(value)[0]
        
        count = HouseInfo.objects.filter(house_about_id=house['house_about_id'],house_type=1).count()

        bre = BuildingInfo.objects.get(building_id=house['house_about_id'])
        bre.building_idle_count = count
        bre.save()
        
    except Exception as e:
        return JsonResponse({
            'ret': 1,
            'msg': "注销失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0})
